<?php
namespace App\Http\Controllers\Admin;

use App\Service\Admin\TmpUserService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;
use ZipArchive as Zip;

class TmpUserController extends BaseController
{
    //用户项目库

    public function __construct(TmpUserService $service)
    {
        $this->db = $service;
    }

    //领取模板
    public function apply(Request $request)
    {
        $token = $request->post('token', '');
        $uid = $this->db->getUidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '没有登录');
        }
        $item_id = $request->post('item_id', 0);
        $resCopy = $this->db->copyByUid($uid, $item_id); //复制项目
        if ($resCopy['code'] < 0) {
            return $this->toJson(-2, $resCopy['msg']);
        }
        //复制到项目目录
        $oldDir = 'ai_items/'.$resCopy['data']['serialOld'];
        $newDir = 'ai_items/'.$resCopy['data']['serialNew'];
        $this->copydir($oldDir, $newDir);
        if (!file_exists($newDir)) {
            return $this->toJson(-2, '项目目录失败');
        }
        return $this->toJson();
    }

    //列表
    public function getIndex(Request $request)
    {
        //$logid = $this->db->tmpLogAdd($request->all());
        $res = $this->db->getIndex();
        //$this->db->tmpLogModify($logid, $res);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //复制目录
    public function copydir($src, $dst)
    {
        if (!file_exists($dst)) mkdir($dst);
        $handle = opendir($src);
        while (($item=readdir($handle)) !== false) {
            if ($item == '.' || $item == '..') continue;
            $_src = $src.'/'.$item;
            $_dst = $dst.'/'.$item;
            if (is_file($_src)) copy($_src, $_dst);
            if (is_dir($_src)) $this->copydir($_src, $_dst);
        }
        closedir($handle);
    }

    //详情
    public function getOne(Request $request)
    {
        $item_id = $request->post('item_id', 0);
        //$logid = $this->db->tmpLogAdd($request->all());
        $res = $this->db->getOne($item_id);
        //$this->db->tmpLogModify($logid, $res);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //读取文件内容
    public function fileRead(Request $request)
    {
        $fid = $request->post('fid', 0);
        $res = $this->db->getFileOne($fid);
        if (empty($res)) {
            return $this->toJson(-2, '没有文件地址');
        }
        if (!file_exists($res['url'])) {
            return $this->toJson(-2, '没有文件');
        }
        $fdetail = file_get_contents($res['url']);
        return $this->toJson(0, '', $fdetail);
    }

    //保存文件
    public function fileSave(Request $request)
    {
//        $token = $request->post('token', '');
//        $uid = $this->db->getUidByToken($token);
//        if (!$uid) {
//            return $this->toJson(-2, '没有登录');
//        }
        $fid = $request->post('fid', 0);
        $fdetail = $request->post('fdetail', '');
        $res = $this->db->getFileOne($fid);
        if (empty($res)) {
            return $this->toJson(-2, '没有文件地址');
        }
        if (!$fdetail) {
            return $this->toJson(-2, '没有文件内容');
        }
        if (!file_exists($res['url'])) {
            return $this->toJson(-2, '没有文件');
        }
        file_put_contents($res['url'], $fdetail);
        return $this->toJson();
    }

    //导出
    public function export(Request $request)
    {
        $token = $request->post('token', '');
        $uid = $this->db->getUidByToken($token);
        if (!$uid) {
            return $this->toJson(-2, '没有登录');
        }
        $item_id = $request->post('item_id', 0);
        $res = $this->db->getOne($item_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        //拷贝接口工程
        $startDir = env('ITEM_PATH').'public/ai_items/lumen';
        $endDir = env('ITEM_PATH').'public/ai_items/'.$res['data']['serial'].'/api';
        if (env('OS') == 'linux') {
            exec("cp -R \"$startDir\" \"$endDir\"", $output, $rstVar);
            if ($rstVar != 0) {
                return $this->toJson(-2, '接口配置失败');
            }
        } else {
            exec("xcopy /E /I \"$startDir\" \"$endDir\"", $output, $rstVar);
            if ($rstVar != 0) {
                return $this->toJson(-2, '接口配置失败');
            }
        }
        //获取打包名称
        $fname = $res['data']['serial'];
        $sourceDir = 'ai_items/'.$res['data']['serial'];
        if (!file_exists($sourceDir)) {
            return $this->toJson(-2, '文件不存在');
        }
        //压缩
        $randTime = time();
        if (!class_exists('ZipArchive')) {
            return $this->toJson(-2, '压缩程序没有安装');
        }
        $targetDir = env('ITEM_PATH').'public/'.$sourceDir.'_'.$randTime.'.zip';
//        $zip = new Zip();
//        if (!$zip->open($targetDir, Zip::CREATE | Zip::OVERWRITE)) {
//            return $this->toJson(-2, "无法打开压缩包 $targetDir");
//        }
//        $this->addFileToZip($sourceDir, $zip);
//        $zip->close();
        $this->addFileToZip($sourceDir, $targetDir);
        $fpath = env('DOMAIN').'/api/admin/tmp/user/down?zipName='.$fname.'_'.$randTime.'.zip';
        $zipId = $this->db->rarAdd($uid, $item_id, $fpath);
        $fpath .= '&zipId='.$zipId;
        return $this->toJson(0, '', $fpath);
    }

    /**
     * 压缩目录
     */
    public function addFileToZip($sourceDir, $destinationZip)
    {
        $zip = new Zip();
        // 打开压缩文件，如果文件不存在则创建新的压缩文件
        if ($zip->open($destinationZip, \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE) !== true) {
            return false;
        }
        // 递归遍历目录，将文件添加到压缩文件中
        $files = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($sourceDir),
            \RecursiveIteratorIterator::LEAVES_ONLY
        );
        foreach ($files as $name => $file) {
            // 跳过目录
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();
                // 相对路径，用于在压缩文件中存放目录结构
                $relativePath = substr($filePath, strlen($sourceDir) + 1);
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();
        return true;
    }

//    /**
//     * 压缩目录
//     * @param string $path 相对地址
//     * @param string $fpath 相对地址
//     * @param object $zip 压缩对象
//     */
//    public function addFileToZip($path, $zip)
//    {
//        $handle = opendir($path);
//        while (($fname=readdir($handle)) !== false) {
//            $dirName = $path.'/'.$fname;
//            if (!in_array($fname, ['.', '..'])) {
//                if (is_dir($dirName)) {
//                    $zip->addEmptyDir($dirName);
//                    $this->addFileToZip($dirName, $zip);
//                }
//                if (is_file($dirName)) {
//                    $zip->addFile($dirName, basename($dirName));
//                }
//            }
//        }
//        @closedir();
//    }

    //下载zip
    public function down(Request $request)
    {
        $zipName = $request->get('zipName', '');
        $zipId = $request->get('zipId', 0);
        $this->db->rarDown($zipId);
        $zipName = 'ai_items/'.$zipName;
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename=' . basename($zipName));
        header('Content-Length: '. filesize($zipName));
        readfile($zipName);
    }

    //文档列表
    public function getDocIndex(Request $request)
    {
//        $token = $request->post('token', '');
//        $uid = $this->db->getUidByToken($token);
//        if (!$uid) {
//            return $this->toJson(-2, '没有登录');
//        }
        $item_id = $request->post('item_id', 0); //项目ID
        $client_type = $request->post('client_type', 0); //用户端类型
        $res = $this->db->getDocIndex($item_id, $client_type);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //详情
    public function getDocOne(Request $request)
    {
        $doc_id = $request->post('doc_id', 0);
        $res = $this->db->getDocOne($doc_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }
}